import React, { useState, useEffect } from "react";
import { View, StyleSheet, Dimensions, Text, Image } from "react-native";
import { Input } from "@rneui/themed";
import { useDispatch } from "react-redux";
import IconNavBar from '@/components/IconNavBar'
import { sectokenImportProps } from '@/config/navigatorProps'
import { PayWithArray, LabelArray } from '@/config/config'
import CheckedImg from '@/assets/safe/checked.png'
import { getValue, setObjectValue } from '@/utils/deviceStorage'
import { guid } from '@/utils/util'
import api from "@/request/api";
import Loading from "@/components/LoadingModal";

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const SectokenImportName = (props) => {

    const dispatch = useDispatch();
    const [safeName, setSafeName] = useState('')
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [importSafeData, setImportSafeData] = useState({});

    useEffect(() => {
        let params = props.route.params
        if (params && params.importSafeData) {
            setImportSafeData(params.importSafeData)
        }
    }, [props]);

    const handlePressLeft = () => {
        props.navigation.goBack()
    }

    const handlePressRightTitle = () => {
        if (safeName && importSafeData && importSafeData.address) {
            setLoadingVisible(true)
            api.get_safe_details_by_address(importSafeData.address).then(res => {
                if (res && res.address) {
                    let profileImg = Object.keys(PayWithArray)[Math.floor(Math.random() * 3)]
                    let label = LabelArray[Math.floor(Math.random() * 7)]
                    let ownerArr = res.owners.map((item, index) => {
                        let obj = {
                            profileImg,
                            label: `${label}${index + 1}`,
                            address: item.value
                        }
                        return obj
                    })
                    let safeWallet = {
                        id: guid(),
                        address: importSafeData.address,
                        label: safeName,
                        ownerList: ownerArr,
                        payWith: {},
                        feeData: {},
                        ownerNumber: res.threshold,
                        profileImg: importSafeData.profileImg
                    }
                    let result = getValue('safeWalletList')
                    let arr = []
                    if (result && result.length > 0) {
                        result.push(safeWallet)
                        arr = result
                    } else {
                        arr.push(safeWallet)
                    }
                    setObjectValue('safeWalletList', [...arr])
                    dispatch({ type: "setSelectedSafeWallet", value: safeWallet || {} });
                    setLoadingVisible(false)
                    props.navigation.navigate({
                        name: 'safe-main',
                        params: {
                            load: true
                        }
                    })
                }
            })
        }
    }

    return (
        <View style={styles.container}>
            <IconNavBar {...props} {...sectokenImportProps} handlePressLeft={handlePressLeft} handlePressRightTitle={handlePressRightTitle} />
            <View style={styles.bodyContent}>
                <Image source={PayWithArray[importSafeData.profileImg]} style={styles.img1} />
                <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
                    <Image source={CheckedImg} style={styles.img2} />
                    <Text style={{ ...styles.title, color: '#2C2C2C', width: 242 * ratio, marginLeft: 8 * ratio }}>{importSafeData.address}</Text>
                </View>
                <Text style={{ ...styles.title, color: '#2C2C2C', width: 299 * ratio, marginTop: 21 * ratio, textAlign: 'center' }}>
                    Choose a name for the Safe.The name is only
                    stored locally and will not be shared with
                    sectoken or any third parties.
                </Text>
                <Input
                    containerStyle={{ ...styles.text_input, paddingLeft: 10 * ratio, marginTop: 21 * ratio }}
                    onChangeText={text => setSafeName(text)}
                    value={safeName}
                    placeholder='Enter name'
                    placeholderTextColor='#AEAEAE'
                    inputContainerStyle={{ borderBottomWidth: 0 }}
                    inputStyle={{ fontSize: 14 }}
                />
            </View>
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FFFFFF'
    },
    bodyContent: {
        flex: 1,
        alignItems: 'center'
    },
    title: {
        fontSize: 14,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        lineHeight: 20
    },
    addressContent: {
        width: 330 * ratio,
        minHeight: 56 * ratio,
        marginTop: 15 * ratio,
        borderWidth: 1,
        borderRadius: 5
    },
    img1: {
        width: 36 * ratio,
        height: 36 * ratio,
        marginTop: 20 * ratio
    },
    img2: {
        width: 16 * ratio,
        height: 16 * ratio
    },
    text_input: {
        width: 330 * ratio,
        height: 48 * ratio,
        borderWidth: 1,
        borderColor: '#AEAEAE'
    },
})
export default SectokenImportName